import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:package_info_plus/package_info_plus.dart';
// import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../style/app_style.dart';
import 'version_manager.dart';

// class VersionDaiLog extends StatefulWidget {
//   const VersionDaiLog({super.key,required this.url});
//   final String url;
//   @override
//   State<VersionDaiLog> createState() => _VersionDaiLogState();
// }
//
// class _VersionDaiLogState extends State<VersionDaiLog> {
//
//   bool _isInstall = false;
//   double _downloadProgress = 0;
//   String _progressText = '';
//   String _apkFilePath = '';
//   DownloaderManager manager = DownloaderManager();
//
//   @override
//   void initState() {
//     super.initState();
//     _downloadApk();
//   }
//   @override
//   Widget build(BuildContext context) {
//     return  Column(
//       mainAxisAlignment: MainAxisAlignment.spaceAround,
//       crossAxisAlignment: CrossAxisAlignment.center,
//       mainAxisSize: MainAxisSize.min,
//       children: <Widget>[
//         Text("下载中,请不要退出"),
//         Row(children: [
//           SizedBox(width: 10),
//           LinearProgressIndicator(value: _downloadProgress,color: AppColor.primaryColor,).addExpand(),
//           SizedBox(width: 10),
//           Text(_progressText),
//           SizedBox(width: 10),
//         ],)
//       ],
//     ).addContainer(color: AppColor.backGroundColor,margin: EdgeInsets.all(20),height: 100).addCenter();
//   }
//
//   Future<void> _downloadApk() async {
//
//     var cacheDir = await getApplicationDocumentsDirectory();
//     var filePath = "${cacheDir.path}/packages/${widget.url.split("/").last}";
//     _apkFilePath = filePath;
//     // _install();
//     // return;
//     manager.downloadFiles([widget.url], "packages",isCache: true,callBack: (process,state){
//       var value = process.replaceAll("%", "");
//       _downloadProgress = double.parse(value) / 100.0;
//       if(state == true){
//         _progressText = "安装中";
//         _install();
//       }else {
//         _progressText = process;
//       }
//       setState(() {
//
//       });
//     });
//     manager.modelCallback = (process,state,{model}){
//
//     };
//   }
//
//   _install()async{
//     final res = await InstallPlugin.install(_apkFilePath ?? '');
//     if(res['isSuccess'] == true){
//       _isInstall = true;
//       SmartDialog.showToast("已安装完成");
//     }else{
//       SmartDialog.dismiss();
//       WidgetUtil.showDialog("安装失败", "是否重新安装", () {
//         _install();
//       });
//     }
//
//   }
// }
//

class VersionManagerUtil{
 static getVersion(){
    // HttpUtil.restApi.getVersion({"type":Platform.isAndroid ? "android" :"ios","appType":"AYLSV"}).then((value)async {
    //   if(value.code == 200){
    //     var model = value.data;
    //     if(model?.versionCode != null){
    //       PackageInfo packageInfo = await PackageInfo.fromPlatform();
    //       if(_compareVersions(packageInfo.version, model!.versionCode!) < 0){
    //         _strongDialog(model);
    //       }
    //     }
    //   }
    // });
  }

 static _strongDialog(VersionManager model){

   void jumpLinker(){
     var url = Platform.isAndroid ? model.androidUrl : model.iosUrl;
     launchUrl(Uri.parse(url ?? ""));
     // if(Platform.isAndroid) {
     //   SmartDialog.showLoading(builder: (_) =>
     //       VersionDaiLog(url: model.downloadUrl ?? ""));
     // }else{
     //   launchUrl(Uri.parse(model.downloadUrl ?? ""));
     // }
   }
   SmartDialog.show(builder: (ctx){
     return Stack(children: [
       Image.asset((model.forceUpdate == false ? "alert_version1" :"alert_version2").toImgPath()).addContainer(width: 283.w,height: 279.w,color: Colors.transparent),
       Positioned(left: 20,bottom: 20,width: 105,child:
       AppButton.sizeBtn(() {
         SmartDialog.dismiss();
       }, const SizedBox(width: 60,height: 45,),bgColor: Colors.transparent).addVisibility(model.forceUpdate == true)
       ),
       Positioned(right: 20,bottom: 20,width: 105,child:
       AppButton.sizeBtn(() {
         jumpLinker();
       },  const SizedBox(width: 60,height: 45,),bgColor: Colors.transparent).addVisibility(model.forceUpdate == true)
       ),
       Positioned(right: 20,bottom: 20,left: 20,child:
       AppButton.sizeBtn(() {
         jumpLinker();
       },  const SizedBox(width: 60,height: 45,),bgColor: Colors.transparent).addVisibility(model.forceUpdate == false)
       ),

     ],);

   },clickMaskDismiss: false);

   return;
    // WidgetUtil.showDialog("发现版本V${model.versionCode}", model.versionInfo, () {
    //
    //   launchUrl(Uri.parse(model.androidUrl ?? ""));
    //   if(model.forceUpdate == false) {
    //     _strongDialog(model);
    //   }
    //   // }
    // },okText: "立即更新",cancelText: "稍后再说",onlyOne: model.forceUpdate ?? false,clickMaskDismiss: model.forceUpdate);
  }
 static int _compareVersions(String version1, String version2) {
    List<String> parts1 = version1.split('.');
    List<String> parts2 = version2.split('.');
    // 比较每一部分
    int length = (parts1.length > parts2.length) ? parts1.length : parts2.length;
    for (int i = 0; i < length; i++) {
      int num1 = (i < parts1.length) ? int.parse(parts1[i]) : 0;
      int num2 = (i < parts2.length) ? int.parse(parts2[i]) : 0;
      if (num1 > num2) {
        return 1;
      } else if (num1 < num2) {
        return -1;
      }
    }
    // 如果到达这里，说明所有部分都相等
    return 0;
  }
}



